﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.Data.Linq;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;


namespace SampleSite.admin.ajax
{
    /// <summary>
    /// updateApp 的摘要说明
    /// </summary>
    public class updateApp : AjaxHttpHandler
    {
        private class InputData
        {
            [Required]
            public int AppId { get; set; }

            [Required]
            public string AppName { get; set; }

            [Required]
            public string Url { get; set; }

            public string Description { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel(out input);
            if (errors.Count > 0)
                throw new Exception("参数错误");

            using (PermissionContext db = new PermissionContext())
            {
                var app = db.sys_Applications.Where(k => k.A_ID != input.AppId &&
                                                         k.A_CName == input.AppName &&
                                                         k.A_State != 2)
                            .Count();
                if (app != 0)
                {
                    context.Response.Write(JSON.Instance.ToJSON(
                        new JSONResult("failed", "应用名不能重复!")));
                    return;
                }

                db.BeginTransaction();

                db.sys_Applications
                  .Where(k => k.A_ID == input.AppId &&
                              k.A_State != 2)
                  .Update((k) =>
                    new sys_Applications()
                    {
                        A_CName = input.AppName,
                        A_AppUrl = input.Url,
                        A_AppDescription = input.Description
                    });

                db.CommitTransaction();

                context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
            }
        }
    }
}